package com.tepth.maintenancesystem.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.tencent.bugly.beta.Beta;
import com.tepth.maintenancesystem.R;
import com.tepth.maintenancesystem.SysApplication;
import com.tepth.maintenancesystem.api.HttpClient;
import com.tepth.maintenancesystem.api.LoginHttp;
import com.tepth.maintenancesystem.bean.User;
import com.tepth.maintenancesystem.untils.ToastUtils;
import com.tepth.maintenancesystem.untils.Untils;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, PopupWindow.OnDismissListener {

    @BindView(R.id.login_linearLayout)
    LinearLayout mLoginLinearLayout; // 登录内容的容器

    @BindView(R.id.userId_LinearLayout)
    LinearLayout mUserIdLinearLayout; // 将下拉弹出窗口在此容器下方显示

    @BindView(R.id.linear_loginLoading)
    LinearLayout linear_loginLoading; // 登录后的Loading布局

    @BindView(R.id.linear_start)
    LinearLayout linear_start;// 启动加载过度页面

    @BindView(R.id.login_edtId)
    EditText mIdEditText; // 登录ID编辑框

    @BindView(R.id.login_edtPwd)
    EditText mPwdEditText; // 登录密码编辑框

    @BindView(R.id.login_more_user)
    ImageView mMoreUser; // 下拉图标

    private String mIdString;
    private String mPwdString;
    private ArrayList<User> mUsers; // 用户列表
    private ListView mUserIdListView; // 下拉弹出窗显示的ListView对象
    private UserAdapter mAdapter; // ListView的监听器
    private PopupWindow mPop; // 下拉弹出窗
    private Context context;
    private String loginResult = "";
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        SysApplication.getInstance().addActivity(this);
        context = this;
        ButterKnife.bind(this);
        Intent intent = getIntent();
        if(intent.getStringExtra("manual")!=null){
            // 动画结束,隐藏启动动画界面
            linear_start.setVisibility(View.GONE);
            mLoginLinearLayout.setVisibility(View.VISIBLE);
            linear_loginLoading.setVisibility(View.GONE);
            initLogin();
        }else{
//            autoLogin();
            initStartAnimation();
        }
        setListener();
    }

    private void autoLogin() {
        new Thread() {
            @Override
            public void run() {
                loginResult = LoginHttp.login(context);//自动登录
                myHandler.sendEmptyMessage(0);
                super.run();
            }
        }.start();
    }

    /**
     * 初始化开始动画
     */
    private void initStartAnimation() {
        // 渐变展示启动屏
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.wel_start);
        linear_start.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {// 动画监听

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
//                autoLogin();
//                // 动画结束,隐藏启动动画界面
//                linear_start.setVisibility(View.GONE);
//                mLoginLinearLayout.setVisibility(View.GONE);
//                linear_loginLoading.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 初始化下拉框
     */
    public void initPop() {
        int width = mUserIdLinearLayout.getWidth() - 4;
        int height = ViewGroup.LayoutParams.WRAP_CONTENT;
        mPop = new PopupWindow(mUserIdListView, width, height, true);
        mPop.setOnDismissListener(this);// 设置弹出窗口消失时监听器
        // 注意要加这句代码，点击弹出窗口其它区域才会让窗口消失
        mPop.setBackgroundDrawable(new ColorDrawable(0xffffffff));
    }

    /**
     * 初始化登陆框
     */
    private void initLogin() {
        Animation loginIn_animation; // login控件进入页面动画
        loginIn_animation = AnimationUtils.loadAnimation(context, R.anim.login_in); // 初始化动画对象
        mLoginLinearLayout.startAnimation(loginIn_animation); // Y轴水平移动

         /* 获取已经保存好的用户密码 */
        mUsers = Untils.getUserList(context);
        if (mUsers.size() > 0) {
            int index = Untils.getUserIndex(context);
            /* 将列表中的第一个user显示在编辑框 */
            mIdEditText.setText(mUsers.get(index).getId());
            mPwdEditText.setText(mUsers.get(index).getPwd());
            mIdString=mUsers.get(index).getId();
            mPwdString=mUsers.get(index).getPwd();
        }
        LinearLayout parent = (LinearLayout) getLayoutInflater().inflate(
                R.layout.userifo_listview, null);
        mUserIdListView = (ListView) parent.findViewById(R.id.list);
        parent.removeView(mUserIdListView); // 必须脱离父子关系,不然会报错
        mUserIdListView.setOnItemClickListener(this); // 设置点击事
        mAdapter = new UserAdapter(mUsers);
        mUserIdListView.setAdapter(mAdapter);
    }

    /**
     * 开启监听
     */
    private void setListener() {
        mIdEditText.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                mIdString = s.toString();
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        mPwdEditText.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                mPwdString = s.toString();
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        Beta.checkUpgrade();
    }

    /**
     * 登录按钮点击事件
     */
    private void clickLogin() {
        if (mIdString == null || mIdString.equals("")) { // 账号为空时
            ToastUtils.showToast(context, "请输入账号");
            return;
        } else if (mPwdString == null || mPwdString.equals("")) {// 密码为空时
            ToastUtils.showToast(context, "请输入密码");
            return;
        }
        Animation loginOut_animation; // login控件进入页面动画
        loginOut_animation = AnimationUtils.loadAnimation(context,
                R.anim.login_out); // 初始化动画对象
        mLoginLinearLayout.startAnimation(loginOut_animation); // Y轴水平移动
        loginOut_animation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                loadingDialog = new LoadingDialog(context);
                loadingDialog.setInterceptBack(false)
                        .setLoadingText("正在加载...");
                loadingDialog.show();
                new Thread() {
                    public void run() {
                        try {
                            User user = new User(mIdString, mPwdString);
                            loginResult = LoginHttp.login(context, user);
                            myHandler.sendEmptyMessage(1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
    }

    @OnClick({R.id.login_btnLogin,R.id.login_more_user})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.login_btnLogin:
                clickLogin();
                break;
            case R.id.login_more_user: // 当点击下拉栏
                if (mPop == null) {
                    initPop();
                }
                if (!mPop.isShowing() && mUsers.size() > 0) {
                    // Log.i(TAG, "切换为角向上图标");
                    mMoreUser.setImageResource(R.drawable.login_more_down); // 切换图标
                    mPop.showAsDropDown(mUserIdLinearLayout, 2, 1); // 显示弹出窗口
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        mIdEditText.setText(mUsers.get(position).getId());
        mPwdEditText.setText(mUsers.get(position).getPwd());
        mIdString=mUsers.get(position).getId();
        mPwdString=mUsers.get(position).getPwd();
        mPop.dismiss();
    }

    @Override
    public void onDismiss() {
        mMoreUser.setImageResource(R.drawable.login_more_up);
    }

    /* ListView的适配器 */
    class UserAdapter extends ArrayAdapter<User> {

        public UserAdapter(ArrayList<User> users) {
            super(context, 0, users);
        }

        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.user_item,
                        null);
            }

            TextView userIdText = (TextView) convertView
                    .findViewById(R.id.listview_userid);
            userIdText.setText(getItem(position).getId());

            ImageView deleteUser = (ImageView) convertView
                    .findViewById(R.id.login_delete_user);
            deleteUser.setOnClickListener(new View.OnClickListener() {
                // 点击删除deleteUser时,在mUsers中删除选中的元素
                @Override
                public void onClick(View v) {
                    mPop.dismiss();
                    if (getItem(position).getId().equals(mIdString)) {
                        //TODO
                        // 如果要删除的用户Id和Id编辑框当前值相等，则清空
                        mIdString = "";
                        mPwdString = "";
                        mIdEditText.setText(mIdString);
                        mPwdEditText.setText(mPwdString);
                        Untils.setUserIndex(context,0);
                    }
                    mUsers.remove(getItem(position));
                    try {
                        Untils.saveUserList(context, mUsers);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mAdapter.notifyDataSetChanged(); // 更新ListView
                }
            });
            return convertView;
        }
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
           if(msg.what==1){
               // 动画结束,隐藏启动动画界面
               linear_start.setVisibility(View.GONE);
               mLoginLinearLayout.setVisibility(View.GONE);
               linear_loginLoading.setVisibility(View.VISIBLE);
           }
            if (loadingDialog != null)
                loadingDialog.close();
            if (loginResult == HttpClient.SUCCESS) {//自动登录成功
                Intent intent = new Intent(context, MaintainListActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            } else if (loginResult == HttpClient.ERROR_VERSION) {//版本提示
//                LoginHttp.checkVersion(context);
            } else {//if (loginResult == HttpClient.NO_USER)
                if (loginResult == HttpClient.ERROR_NET) {
                    ToastUtils.showToast(context, "请检查您的网络");
                }
                switch (msg.what) {
                    case 0://自动登录
                        // 动画结束,隐藏启动动画界面
                        linear_start.setVisibility(View.GONE);
                        mLoginLinearLayout.setVisibility(View.VISIBLE);
                        linear_loginLoading.setVisibility(View.GONE);
                        initLogin();
                        break;
                    case 1://手动登录
                        ToastUtils.showToast(context, loginResult);
                        linear_start.setVisibility(View.GONE);
                        mLoginLinearLayout.setVisibility(View.VISIBLE);
                        linear_loginLoading.setVisibility(View.GONE);
                        break;
                }
            }
            super.handleMessage(msg);
        }
    };
    private long exitTime = 0;
    // 退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.showToast(context,"再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                SysApplication.getInstance().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
